import type { Report } from "@server/src/schemas/reports";
import type { Test } from "@server/src/schemas/tests";
import {
  type ColumnFiltersState,
  getCoreRowModel,
  getFacetedRowModel,
  getFacetedUniqueValues,
  getFilteredRowModel,
  useReactTable,
} from "@tanstack/react-table";
import { useEffect, useState } from "react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { TestsColumns } from "./tests-columns";
import { TestsDataTable } from "./tests-data-table";
import { TestsDetail } from "./tests-detail";
import { TestsFilter } from "./tests-filter";
import { TestsSummary } from "./tests-summary";

type Tab = "all" | "failed" | "passed";

export function TestsTable({ report, tests }: { report: Report; tests: Test[] }) {
  const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
  const [activeTab, setActiveTab] = useState<Tab>("all");

  useEffect(() => {
    setColumnFilters((prev) => {
      const rest = prev.filter((f) => f.id !== "status");
      if (activeTab === "failed")
        return [...rest, { id: "status", value: ["skipped", "failed", "broken", "unknown"] }];
      if (activeTab === "passed") return [...rest, { id: "status", value: ["passed"] }];
      return rest;
    });
  }, [activeTab]);

  const table = useReactTable<Test>({
    data: tests,
    columns: TestsColumns,
    state: { columnFilters },
    onColumnFiltersChange: setColumnFilters,
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getFacetedRowModel: getFacetedRowModel(),
    getFacetedUniqueValues: getFacetedUniqueValues(),
    initialState: { columnVisibility: { status: false } },
    defaultColumn: {
      size: 120,
      minSize: 80,
      maxSize: 700,
    },
  });

  return (
    <div className="grid h-full w-full grid-cols-3 gap-4">
      <div className="col-span-2 flex h-full flex-col gap-4">
        <TestsSummary report={report} tests={tests} />
        <Tabs
          defaultValue="all"
          className="h-full w-full"
          onValueChange={(v) => setActiveTab(v as Tab)}
        >
          <div className="grid grid-cols-2 gap-4">
            <TabsList>
              {(["all", "passed", "failed"] as Tab[]).map((t) => (
                <TabsTrigger key={t} value={t} className="capitalize">
                  {t}
                </TabsTrigger>
              ))}
            </TabsList>
            <TestsFilter table={table} />
          </div>
          <TabsContent value={activeTab} className="h-full">
            <ScrollArea className="h-full w-full rounded-xl border bg-card shadow-sm">
              <TestsDataTable table={table} />
            </ScrollArea>
          </TabsContent>
        </Tabs>
      </div>
      <ScrollArea className="h-full w-full rounded-xl border bg-card shadow-sm">
        <TestsDetail />
      </ScrollArea>
    </div>
  );
}
